package site.hanzhe.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.hanzhe.dao.MenuDao;
import site.hanzhe.entity.MenuEntity;
import site.hanzhe.service.MenuService;

import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public List<MenuEntity> selectList() {
        return menuDao.selectList(null);
    }

    @Override
    public MenuEntity selectTree() {
        List<MenuEntity> list = menuDao.selectList(null);
        MenuEntity root = null;
        // 找到父节点并从集合中删除该节点
        for (Iterator<MenuEntity> iterator = list.iterator(); iterator.hasNext(); ){
            MenuEntity entity = iterator.next();
            if ( entity.getPid() == null ){
                entity.setOpen(true);
                root = entity;
                iterator.remove();
                break;
            }
        }
        // 遍历所有二级节点并从集合中删除二级节点
        for (Iterator<MenuEntity> iterator = list.iterator(); iterator.hasNext();) {
            MenuEntity entity = iterator.next();
            if ( root.getId().equals(entity.getPid()) ){
                entity.setOpen(true);
                root.getChildren().add(entity);
                iterator.remove();
            }
        }
        // 遍历获取所有的三级节点
        for (MenuEntity two : root.getChildren()) {
            for (MenuEntity three : list) {
                if ( two.getId().equals(three.getPid()) )
                    two.getChildren().add(three);
            }
        }
        return root;
    }

    @Override
    public int insertMenu(MenuEntity entity) {
        return menuDao.insert(entity);
    }

    @Override
    public int updateMenu(MenuEntity entity) {
        return menuDao.updateById(entity);
    }

    @Override
    public int deleteMenuById(String id) {
        return menuDao.deleteById(id);
    }

}
